package per.ace.transactional.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import per.ace.transactional.pojo.User;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

/**
 * @program: springbootDemo
 * @description: user service
 * @author: ace
 * @Date: 2020-04-06 12:56
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //add user
    @Transactional
    public void addUser(User user) {
        jdbcTemplate.execute("insert tb_user values ('" + user.getUserId() + "','" + user.getUserName() + "')");
        jdbcTemplate.execute("insert tb_log values ('" + UUID.randomUUID() + "','新增用户:" + user.getUserId() + "',now())");
        //人造异常
        int a = 1 / 0;
    }

    @Autowired
    DataSource dataSource;

    public void deleteUser(Long userId) throws SQLException {
        //获取jdbc链接
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);//默认为自动提交 设置为手动提交
        Statement statement = connection.createStatement();

        try {
            statement.execute("delete from tb_user where user_id ='" + userId + "'");
            statement.execute("insert tb_log values ('" + UUID.randomUUID() + "','删除用户:" + userId + "',now())");

            //人造异常
            int a = 1 / 0;

            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            log.error("出现异常,回滚");
            e.printStackTrace();
        }

    }
}
